<template>
	<view class="h-fill pad content">
		<u-navbar title="我的票券" titleColor="#fff" backIconColor="#fff" :background="navBg"></u-navbar>
		<view v-if="tickets.length">
			<view v-for="(ticket, index) in tickets" :key="index" class="ticket" :style="{height: ticketHeight + 'px'}">
				<image v-if="ticket.status !== 3" class="h-fill v-fill" src="static/img/img_piaoquan_bg@2x.png" mode="aspectFit"></image>
				<image v-else class="h-fill v-fill" src="./static/img/img_guoqi_bg@2x.png" mode="aspectFit"></image>
				<view class="ticket-content uni-flex uni-column l-pad r-pad">
					<view class="uni-flex align-center" :style="{height: ticketHeaderHeight + 'px'}">
						<view class="uni-flex-extend uni-flex align-center">
							<text class="uni-text-big" :class="{'ticket-name': ticket.status !== 3, 'uni-text-gray': ticket.status === 3}">{{ticket.name}}</text>
							<text v-if="ticket.getWays === 'EXCHANGE'" class="uni-text-big" :class="{'ticket-name': ticket.status !== 3, 'uni-text-gray': ticket.status === 3}">(兑)</text>
							<text v-else-if="ticket.getWays === 'GROUP'" class="uni-text-big" :class="{'ticket-name': ticket.status !== 3, 'uni-text-gray': ticket.status === 3}">(拼)</text>
						</view>
						<view v-if="ticket.status === 0" hover-class="uni-list-cell-hover">
							<view class="btn uni-text-small" @click="handleClick(index)">去使用</view>
						</view>
						<view v-else-if="ticket.status === 4" class="btn btn-disable uni-text-small">已退票</view>
						<view v-else class="btn btn-disable uni-text-small">已使用</view>
					</view>
					<view class="ticket-bot uni-flex-extend uni-flex uni-column">
						<view class="uni-text-gray uni-flex">
							<text class="uni-text-gray">适用门店：</text>
							<text @click="navToStoreList(ticket)" style="color: #3E62FF;">查看</text>
						</view>
						<view class="uni-text-gray">可用时间：{{ticket.validTime || "无限制"}}</view>
						<view class="uni-text-gray">截止时间：{{ticket.deadline || "无限制"}}</view>
					</view>
				</view>
				<image v-if="ticket.status === 3" class="ticket-dead" mode="aspectFit" src="static/img/img_guoqi@2x.png"></image>
			</view>
			<uni-load-more :status="loadingStatus"></uni-load-more>
		</view>
		<u-empty v-else></u-empty>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {ticketGetWays} from "../common/constants.js"
	const btnLabels = ["去使用", "已过期"]
	const weekDaysDic = {
		'1': '周一',
		'2': '周二',
		'3': '周三',
		'4': '周四',
		'5': '周五',
		'6': '周六',
		'7': '周日',
		'8': '周一~周日'
	};
	const ticketBgRatio = 2;
	export default {
		data() {
			return {
				ticketGetWays,
				navBg: {
					'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)'
				},
				tickets: [],
				storeList: [],
				pageNum: 0,
				loadingStatus: 'noMore',
				btnLabels,
				ticketHeight: 0,
				ticketHeaderHeight: 0
			}
		},
		computed: mapState(['userInfo']),
		created() {
			let sysInfo = uni.getSystemInfoSync();
			this.ticketHeight = (sysInfo.windowWidth - uni.upx2px(20) * 2) / ticketBgRatio;
			this.ticketHeaderHeight = this.ticketHeight * 115 / 331;
		},
		onShow() {
			this.loadData()
		},
		async onPullDownRefresh() {
			await this.loadData()
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			this.loadMore();
		},
		methods: {
			navToStoreList(item) {
				uni.navigateTo({
					url: "./available-store?ticketId=" + item.id
				})
			},
			handleClick(index) {
				let ticket = this.tickets[index];
				this.$log("ticket", ticket);
				if (ticket.status === 0) {
					uni.navigateTo({
						url: './ticket-code?id=' + ticket.id
					})
				} else {
					//todo
				}
			},
			async loadData() {
				try{
					await this.reload()
				}catch(e){
					//TODO handle the exception
				}
			},
			async reload() {
				if (this.loadingStatus === 'loading') {
					return
				}
				this.tickets = []
				this.pageNum = 0
				this.loadingStatus = 'more'
				await this.loadMore()
			},
			async loadMore() {
				if (this.loadingStatus === 'loading' || this.loadingStatus === 'noMore') {
					return
				}
				let preStatus = this.loadingStatus;
				this.loadingStatus = 'loading'
				let query = {
					pageNum: this.pageNum + 1,
				}
				try {
					let data = await this.$http.getTickets(query)
					if (data.records.length) {
						data.records.forEach(item => {
							this.calcValidTime(item);
						});
						this.$log("tickets", data.records);
						this.tickets = this.tickets.concat(data.records)
						this.pageNum++
					}
					if (data.total > this.tickets.length) {
						this.loadingStatus = 'more'
					} else {
						this.loadingStatus = 'noMore'
					}
				} catch (e) {
					this.loadingStatus = preStatus;
				}
			},
			calcValidTime(ticket) {
				var dayStr = "";
				var onlyOneDay = false;
				if (ticket.useStartDay && ticket.useEndDay) {
					let [year1, month1, day1] = ticket.useStartDay.split("-");
					let [year2, month2, day2] = ticket.useEndDay.split("-");
					if (year1 === year2 && month1 === month2 && day1 === day2) {
						dayStr = `仅限${month1}月${day1}日`;
						onlyOneDay = true;
					} else {
						dayStr = `${month1}-${day1}~${month2}-${day2}`;
					}
				} else if (ticket.useStartDay) {
					let [year, month, day] = ticket.useStartDay.split("-");
					dayStr = `${month}-${day}后`;
				} else if (ticket.useEndDay) {
					let [year, month, day] = ticket.useEndDay.split("-");
					dayStr = `${month}-${day}前`;
				}
				this.$log("day string", dayStr);
				var timeStr = "";
				if (ticket.useStartTime && ticket.useEndTime) {
					let [h1, m1, s1] = ticket.useStartTime.split(":");
					let [h2, m2, s2] = ticket.useEndTime.split(":");
					timeStr = `${h1}:${m1}~${h2}:${m2}`;
				} else if (ticket.useStartTime) {
					let [h, m, s] = ticket.useStartTime.split(":");
					timeStr = `${h}:${m}后`;
				} else if (ticket.useEndTime) {
					let [h, m, s] = ticket.useEndTime.split(":");
					timeStr = `${h}:${m}前`;
				}
				this.$log("time string", timeStr);
				var weekStr = "";
				if (!onlyOneDay && ticket.useWeek) {
					let weekDays = ticket.useWeek.split(",");
					if (weekDays.length === 7) {
						weekStr = "周一~周日";
					} else {
						let t = [];
						weekDays.forEach((item) => {
							t.push(weekDaysDic[item]);
						});
						weekStr = t.join("、");
					}
				}
				ticket.validTime = `${dayStr} ${weekStr} ${timeStr}`.trim();
			},
		}
	}
</script>

<style lang="scss">
	.ticket {
		position: relative;
		margin: 0 0 20rpx 0;
		&-content {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
		}
		&-name {
			color: #FE8816;
		}
		&-bot {
			justify-content: center;
		}
		&-dead {
			position: absolute;
			top: 20rpx;
			right: 40rpx;
			width: 200rpx;
			height: 200rpx;
		}
	}

	.line {
		width: 0px;
		background: rgba(233, 237, 255, 1);
		border: 1px dashed rgba(229, 229, 229, 1);
		align-self: stretch;
	}

	.count {
		color: #9483FC;
	}

	.btn {
		background-color: #D61719;
		color: #fff;
		border-radius: 60rpx;
		padding: 10rpx 40rpx;
	}

	.btn-disable {
		background-color: #B2B2B2;
	}
</style>
